package com.jlcloud.core.oauth2.handler;

import lombok.RequiredArgsConstructor;
import com.jlcloud.core.jwt.JwtUtil;
import com.jlcloud.core.jwt.props.JwtProperties;
import com.jlcloud.core.oauth2.provider.OAuth2Request;
import com.jlcloud.core.oauth2.provider.OAuth2Token;
import com.jlcloud.core.oauth2.service.OAuth2User;

/**
 * JlCloudTokenHandler
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
@RequiredArgsConstructor
public class OAuth2TokenHandler implements TokenHandler {

	private final JwtProperties properties;

	/**
	 * 令牌增强
	 *
	 * @param user    用户信息
	 * @param token   令牌信息
	 * @param request 授权参数
	 * @return OAuth2Token
	 */
	@Override
	public OAuth2Token enhance(OAuth2User user, OAuth2Token token, OAuth2Request request) {

		//令牌状态配置, 仅在生成AccessToken时候执行
		if (properties.getState() && token.hasAccessToken()) {
			JwtUtil.addAccessToken(
				user.getTenantId(),
				user.getClient().getClientId(),
				user.getUserId(),
				token.getAccessToken(),
				token.getAccessTokenExpire()
			);
		}
		//令牌状态配置, 仅在生成RefreshToken时候执行
		if (properties.getState() && properties.getSingle() && token.hasRefreshToken()) {
			JwtUtil.addRefreshToken(
				user.getTenantId(),
				user.getClient().getClientId(),
				user.getUserId(),
				token.getRefreshToken(),
				token.getRefreshTokenExpire()
			);
		}

		// 返回令牌
		return token;
	}
}
